package com.LachesismStorm.lachesism.downloader;

import com.LachesismStorm.lachesism.core.util.AsyncUtil;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class sissyhypnoImageDownloader {
    public static void main(String[] args) {
        ArrayList<String> pageUrls = new ArrayList<>();
        pageUrls.add("https://sissyhypno.com/most-viewed/");
        for (int i = 2; i < 32; i++) {
            String url = "https://sissyhypno.com/most-viewed/page" + i + ".html";
            pageUrls.add(url);
        }
        for (String pageUrl : pageUrls) {
            AsyncUtil.executeAsync(() -> {
                a(pageUrl);
            });
        }

    }

    @SneakyThrows
    public static void a(String pageUrl) {
        // 获取页面中符合条件的所有链接
        List<String> links = getLinksFromPage(pageUrl);
        // 输出所有链接并处理每个链接
        for (String link : links) {
            System.out.println("正在处理链接: " + link);
            // 获取视频源链接
            String videoSrc = getVideoSource(link);

            if (videoSrc != null) {
                // 获取页面标题作为文件名
                String fileName = getFileName(link);
                System.out.println("文件名: " + fileName);
                AsyncUtil.executeAsync(() -> {
                    // 下载视频并保存
                    try {
                        downloadVideo(videoSrc, fileName);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });

            } else {
                System.out.println("未找到视频源链接");
            }
        }
    }


    // 获取页面中符合选择器规则的所有 href 链接
    public static List<String> getLinksFromPage(String pageUrl) throws IOException {
        List<String> links = new ArrayList<>();

        // 获取页面的HTML内容
        Document document = Jsoup.connect(pageUrl).get();

        // 定义选择器规则
        String selector = "body > section.page-wrap > section.content-sec > div > div:nth-child(2) > div > div > main > div > div > div > div > div > div > a:nth-child(1)";

        // 获取符合条件的所有 <a> 标签
        Elements linkElements = document.select(selector);

        // 遍历所有元素，提取 href 属性
        for (Element linkElement : linkElements) {
            String href = linkElement.attr("href");
            if (!href.isEmpty()) {
                links.add(href);  // 存入列表
            }
        }
        return links;
    }

    // 获取页面中的视频源链接（#thisPlayer > source > src）
    public static String getVideoSource(String pageUrl) throws IOException {
        Document document = Jsoup.connect(pageUrl).get();

        // 选择器：获取视频源
        Element videoElement = document.select("#thisPlayer > source").first();
        if (videoElement != null) {
            return videoElement.attr("src");  // 返回视频的src链接
        }
        return null;  // 如果没有找到视频源，返回null
    }

    // 获取页面中的标题（body > section.page-wrap > section.content-sec > div > div:nth-child(2) > div > div > main > div > div:nth-child(1) > div > div > div:nth-child(3) > div > h1）
    public static String getFileName(String pageUrl) throws IOException {
        Document document = Jsoup.connect(pageUrl).get();

        // 选择器：获取标题
        Element titleElement = document.select("body > section.page-wrap > section.content-sec > div > div:nth-child(2) > div > div > main > div > div:nth-child(1) > div > div > div:nth-child(3) > div > h1").first();
        if (titleElement != null) {
            return titleElement.text().trim().replaceAll("[^a-zA-Z0-9]", "_");  // 文件名只包含字母数字和下划线
        }
        return "default_title";  // 如果找不到标题，返回默认文件名
    }

    // 下载视频并保存到本地
    public static void downloadVideo(String videoUrl, String fileName) throws IOException {
        // 目标文件夹路径
        String downloadDir = "/Users/yuno/Downloads/video";
        fileName = fileName.replaceAll("_", " ");
        fileName = fileName.replaceAll("   ", "-");
        // 确保目标文件夹存在
        File dir = new File(downloadDir);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                System.err.println("无法创建目标目录: " + downloadDir);
                return;
            }
        }

        // 设置视频文件保存路径
        File videoFile = new File(downloadDir, fileName + ".mp4");

        // 获取视频链接
        URL url = new URL(videoUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");

        // 获取输入流
        try (InputStream inputStream = connection.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(videoFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("视频下载完成：" + videoFile.getAbsolutePath());
        }
    }
}
